package cn.mesmile.flow.config.listen;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.BaseEntityEventListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zb
 * @date 2020/12/25 13:45
 * @Description
 */
@Slf4j
@Component
public class GlobalTaskCompleteListener extends AbstractFlowableEngineEventListener {

    /**
     * {@link BaseEntityEventListener}
     *
     * org.flowable.engine.delegate.event.BaseEntityEventListener: 事件监听器基类，
     * 可用来监听实体（entity）相关事件，特定或所有实体的事件都可以。它隐藏了类型检测，
     * 提供了4个需要覆盖的方法：onCreate(..), onUpdate(..)与onDelete(..)在实体创建、更新及删除时调用；
     * 对所有其他实体相关事件，onEntityEvent(..)会被调用。
     *
     */


    @Override
    protected void taskCompleted(FlowableEngineEntityEvent event) {

        log.info(">>>>>>>>>>>>>>>>>  进入任务完成监听器，{}", DateUtil.now());

        try {
            if (event instanceof FlowableEntityEventImpl) {
                FlowableEntityEventImpl eventImpl = (FlowableEntityEventImpl) event;
                //得到任务实例
                TaskEntity entity = (TaskEntity) eventImpl.getEntity();
                String processInstanceId = event.getProcessInstanceId();
                String assignee = entity.getAssignee();
                String name = entity.getName();

                System.out.println("entity.getTaskDefinitionId() = " + entity.getTaskDefinitionId());
                System.out.println("entity.getTaskDefinitionKey() = " + entity.getTaskDefinitionKey());
                System.out.println("processInstanceId = " + processInstanceId);
                System.out.println("assignee = " + assignee);
                System.out.println("name = " + name);
            }
        } catch (Exception e) {
            log.error("任务结束监听器异常", e);
        }

    }

}
